<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">活动编号：</p>
      <el-input
        v-model="listQuery.num"
        size="small"
        placeholder="请输入商品标题"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        size="small"
        placeholder="请选择状态"
        clearable
        class="filter-item"
        style="width: 250px;margin-left:2%"
        v-model="listQuery.status"
      >
        <el-option v-for="item in qudaoTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;float:right"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
      <el-table-column label="活动编号" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.descr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==="0"?"未开始": scope.row.status==="1"?'进行中':'已结束' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="300px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.beginTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" width="300px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="350px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="danger"
            :disabled='row.status==="1"?false:true'
            @click="handledelete(row)"
          >
            结束
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            align="center"
            type="primary "
            @click="handleDetails(row)"
          >
            活动商品
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
      width="60%"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        :rules="rulesIndex"
        label-position="right"
        label-width="150px"
        style="width: 600px; margin-left:150px;"
      >
        <el-form-item label="活动编号:" v-if="outDialogStatus === 'update'">
          <el-input v-model="temp.num" :disabled="true"/>
        </el-form-item>
        <el-form-item label="开始日期时间:" prop="beginTime">
          <el-date-picker
            v-model="temp.beginTime"
            value-format='yyyy-MM-dd HH:mm:ss'
            type="datetime"
            placeholder="选择开始日期时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期时间:" prop="endTime">
          <el-date-picker
            v-model="temp.endTime"
            value-format='yyyy-MM-dd HH:mm:ss'
            type="datetime"
            placeholder="选择结束日期时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="活动描述：" prop="descr">
          <el-input type="textarea" v-model="temp.descr" />
        </el-form-item>
        <el-form-item label="活动状态：" prop="status">
            <el-radio v-model="temp.status" label="0">未开始</el-radio>
            <el-radio v-model="temp.status" label="1">进行中</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      @close="loadPage"
      :close-on-click-modal="false"
      :visible.sync="detailsVisible"
      append-to-body
      width="85%"

    >
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">商品名称：</p>
      <el-input
        v-model="listShopping.infoName"
        size="small"
        placeholder="请输入商品名称"
        style="width: 200px;float:left"
        class="filter-item"
        @keyup.enter.native="handleFilter1"
      />
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        style="margin-left:3%"
        @click="handleFilter1"
      >
        搜索
      </el-button>
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;float:right"
        type="primary"
        icon="el-icon-edit"
        @click="handleAdd"
      >添加</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="detailList"
      :key="tableKey"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top:1%"
    >
      <el-table-column label="商品名称" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.infoName }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="采购价格" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.purchansePrice/100 }}</span>
          <!-- <img :src="scope.row.infoName" alt=""> -->
        </template>
      </el-table-column>
      <el-table-column label="市场价格" width="200px" align="center">
        <template slot-scope="scope">
          <!-- <img :src="scope.row.imageUrl" style="width:100%;height:100%" alt=""> -->
          <span>{{ scope.row.marketPrice/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平台销售价格" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sellPrice/100}}</span>
        </template>
      </el-table-column>
      <el-table-column label="补贴金额" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.helpPoorMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="350px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="UpdateGoods(row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            align="center"
            type="success"
            @click="shoppingDetails(row)"
          >
            商品详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="detailTotal > 0"
      :total="detailTotal"
      :page.sync="listShopping.pageNum"
      :limit.sync="listShopping.pageSize"
      @pagination="handlePage"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="detailsVisible = false">
        返回
      </el-button>
    </div>
    <el-dialog
      width="60%"
      :title="textMap[outDialogStatus]"
      :visible.sync="innerVisible"
      @close="chearData"
      append-to-body>
      <el-form
        ref="dataForm"
        :model="tempGoods"
        :rules="rules"
        label-position="right"
        label-width="240px"
        style="width: 700px; margin-left:150px;"
      >
        <el-form-item label="活动编号:" v-if="outDialogStatus === 'update'">
          <el-input v-model="rowNum" :disabled="true" />
        </el-form-item>
        <el-form-item label="商品ID(商品查询列表中获取):" prop="proId">
          <el-input style="width:300px" v-model="tempGoods.proId"/>
          <el-button type="primary" style="margin-left:20px;" @click="queryGoods">查询商品</el-button>
        </el-form-item>
        <el-form-item label="商品名称:" v-if="isShow" prop="GoodsName">
          <el-input v-model="GoodsName"/>
        </el-form-item>
        <el-form-item label="商品规格(不同价格)：" v-if="isShow" prop="proType">
           <el-table :data="data1List" tooltip-effect="dark" ref="tableData" @row-click="singleElection" stripe border style="width:100%">
              <el-table-column prop="prop" label="单选" align="center">
                <template slot-scope="scope">
                  <el-radio class="radio" v-model="templateSelection" :label="scope.$index">&nbsp;</el-radio>
                </template>
                 <!-- v-model="scope.row.id == transferForm.selectedId" -->
              </el-table-column>
              <el-table-column label="型号" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.proTitle}}</span>
                </template>
              </el-table-column>
              <el-table-column label="销售价格" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.proSellPrice/100}}</span>
                </template>
              </el-table-column>
              <el-table-column label="采购价格" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.purchansePrice/100}}</span>
                </template>
              </el-table-column>
              <el-table-column label="市场价格" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.proMarketPrice/100}}</span>
                </template>
              </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item label="补贴金额：" prop="helpMoney">
          <el-input-number style="float:left" v-model="tempGoods.helpPoorMoney"></el-input-number>
          <p style="float:left;margin-left:3%">(金额以元为单位)</p>
        </el-form-item>
        <el-form-item label="备注：" prop="remake">
            <el-input v-model="tempGoods.remark"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="outDialogStatus === 'create' ? createCommodity() : updateCommodity()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { getListPage,delOperation,addDataList,updateDataList,getDetails,queryGoods,addGoods,updateGoods,isAdd } from '@/api/activityManage'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件

const qudaoTypeOptions = [
  { key: '0', display_name: '未开始' },
  { key: '1', display_name: '进行中' },
  { key: '2', display_name: '已结束' },
]
const calendarqudaoKeyValue = qudaoTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
export default {
  inject:["reload"],
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    qudaoFilter(type) {
      return calendarqudaoKeyValue[type]
    }
  },
  data() {
    return {
      radio:0,
      templateSelection:'',
      innerVisible:false,
      detailsVisible:false,
      deptValue:'',
      tableKey: 0,
      list: null,
      zhutiList:null,
      imgList:null,
      total: 0,
      zhutiTotal:0,
      rowNum:'',
      imgTotal:0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        num:"",
        status:'',
        sort: '+id',
      },
      listShopping:{
        pageNum: 1,
        pageSize: 10,
        num:'',
        infoName:''
      },
      deps:[],
      info:'',
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        status:""
      },
      tempGoods:{
        sellPrice:"",
        purchansePrice:'',
        marketPrice:'',
        proTitle:'',
        helpPoorId:'',
        proPriceId:''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      outDialogStatus:'',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rowId:"",
      qudaoTypeOptions,
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      downloadLoading: false,
      liaUser: null,
      ids:[],
      idss:[],
      select:null,
      detailList:null,
      detailTotal:0,
      GoodsId:'',
      GoodsName:'',
      data1List:[],
      isShow:false,
      rowObject:{},
      rules: {
          proId: [
            { required: true, message: '请输入商品ID', trigger: 'blur' },
          ],
          GoodsName: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          proType: [
            {  required: true, message: '请选择商品规格', trigger: 'blur' }
          ],
          helpMoney: [
            {  required: true, message: '请输入补贴金额', trigger: 'blur' }
          ],
          remake: [
            {  required: true, message: '请输入备注', trigger: 'blur' }
          ]
        },
        rulesIndex: {
          beginTime: [
            { required: true, message: '请输入开始时间', trigger: 'blur' },
          ],
          endTime: [
            { required: true, message: '请输入结束时间', trigger: 'blur' }
          ],
          descr: [
            { required: true, message: '请输入活动描述', trigger: 'blur' }
          ],
          status: [
            {  required: true, message: '请选择活动状态', trigger: 'change' }
          ],
        }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    loadPage(){
      this.getList()
    },

    chearData(){
      this.isShow=false
    },
    singleElection (row) {
      this.templateSelection = this.data1List.indexOf(row);
      console.log(this.templateSelection)
      this.tempGoods.sellPrice=row.proSellPrice,
      this.tempGoods.purchansePrice=row.purchansePrice,
      this.tempGoods.marketPrice=row.proMarketPrice
      this.tempGoods.proTitle=row.proTitle
      this.tempGoods.proPriceId=row.proPriceId
    },
    getFloor(){
      getFloorData(this.rowId).then(res=>{
        this.checkedList=res.recchecks
        this.imgChecked=res.picchecks
      })
    },
    handlePage(){
      this.handleDetails(this.rowObject)
    },
    handleDetails(row){
        this.rowId=row.id
        this.rowNum=row.num
        this.rowObject=row
        var params = {
            // pageConvert: true,
            pageNum: this.listShopping.pageNum-1,
            pageSize: this.listShopping.pageSize,
            rowId:this.rowId,
            num:this.listShopping.num,
            infoName:this.listShopping.infoName
        }
        getDetails(params).then(res=>{
            this.detailsVisible=true
            this.detailList=res.data.content
            this.detailTotal=res.data.totalElements
        })
    },
    shoppingDetails(row){
		console.log(row)
		this.$router.push({
			path:'/purchase/commodity',
			query:row
		})
    },
    queryGoods(){
      queryGoods(this.tempGoods.proId).then(res=>{
        this.GoodsName=res.data.infoName
        this.data1List=res.data.list
        if(this.data1List.length===0){
          this.isShow=false
        }else{
          this.isShow=true
        }
        this.templateSelection=null
        this.tempGoods.proPriceId=''
        // this.rowId=''
      })
      
    },
    getList() {
      this.listLoading = true
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum-1,
        pageSize: this.listQuery.pageSize,
        num:this.listQuery.num,
        status:this.listQuery.status
      }
      getListPage(params).then(response => {
        this.list = response.data.content
        this.total = response.data.totalElements
        // Just to simulate the time of the request
          this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleFilter1() {
      this.listShopping.page = 1
      this.handlePage()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
      }
    },
    restGoods(){
      this.tempGoods= {
      }
    },
    UpdateGoods(row){
      this.tempGoods = Object.assign({}, row)
      this.outDialogStatus='update'
      this.innerVisible = true
      this.queryGoods()
      this.isShow=true
      console.log(this.tempGoods.helpPoorProdId)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
     handleUpdate(row) {
      this.rowId=row.id
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      updateDataList(this.temp).then(() => {
        for (const v of this.list) {
          if (v.id === this.temp.id) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.temp)
            break
          }
        }
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.reload()
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAdd(){
      this.restGoods()
      this.outDialogStatus='create'
      this.innerVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      addDataList(this.temp).then(() => {
        this.list.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
        this.reload()
      })
    },
    createCommodity(){
      this.tempGoods.helpPoorId=this.rowId
      this.tempGoods.infoName=this.GoodsName
      this.tempGoods.helpPoorMoney=Number(this.tempGoods.helpPoorMoney)
      var params={
        proPriceId:this.tempGoods.proPriceId,
        helpPoorId:this.rowId
      }
      isAdd(params).then(res=>{
        if(res.code==='200'){
          addGoods(this.tempGoods).then(res=>{
            if(res.code==='200'){
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000
                })
            }
            this.innerVisible = false
            this.handlePage()
          })
          this.templateSelection=null
        }
      })
    },
    updateCommodity(){
      this.tempGoods.helpPoorId=this.rowId
      this.tempGoods.infoName=this.GoodsName
      this.tempGoods.helpPoorMoney=Number(this.tempGoods.helpPoorMoney)
      var params={
        proPriceId:this.tempGoods.proPriceId,
        helpPoorId:this.rowId
      }
      isAdd(params).then(res=>{
        if(res.code==='200'){
          updateGoods(this.tempGoods).then(() => {
            for (const v of this.list) {
              if (v.id === this.tempGoods.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.tempGoods)
                break
              }
            }
            // this.dialogFormVisible = false
            this.innerVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
            this.handlePage()
          })
        }
      })
    },
    handledelete(row){
        this.rowId=row.id
        this.$confirm('确定结束？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
            delOperation(this.rowId).then(res=>{
                this.$message({
                type: 'success',
                message: '成功!'
                });
             this.reload()
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });

    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
